/*********************************************************
Copyright:

Copyright (c) 2007, Li Jie (qiezi) cpunion@gmail.com

All rights reserved.<br />

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:<br />

Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. <br />
Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution. <br />
Neither the name of the <ORGANIZATION> nor the names of its contributors 
may be used to endorse or promote products derived from this software without 
specific prior written permission. <br />

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Authors: Li Jie (qiezi) cpunion@gmail.com
Date: March 31, 2007
*********************************************************/


module bdb.environment;


private import bdb.c.db;
private import bdb.exception;
private import bdb.transaction;
private import std.string;
private import std.c.string;
private import std.c.time;


/**
 * Database Environment 
 */
class Environment
{
public:
	enum CreateFlag {
		Default				= 0,
		RpcClient			= DB_RPCCLIENT,
	}

	enum OpenFlag {
		Default				= 0,
		Concurrent			= DB_INIT_CDB,
		Locking				= DB_INIT_LOCK,
		Logging				= DB_INIT_LOG,
		MemoryPool			= DB_INIT_MPOOL,
		Repliaction			= DB_INIT_REP,
		Transaction			= DB_INIT_TXN,
		Recover				= DB_RECOVER,
		RecoverFatal		= DB_RECOVER_FATAL,
		UseEnvironment		= DB_USE_ENVIRON,
		UseEnvironmentRoot	= DB_USE_ENVIRON_ROOT,
		Create				= DB_CREATE,
		Lockdown			= DB_LOCKDOWN,
		Private				= DB_PRIVATE,
		Register			= DB_REGISTER,
		SystemMemory		= DB_SYSTEM_MEM,
		Thread				= DB_THREAD
	}

	enum CloseFlag {
		Default				= 0
	}

	enum RemoveFlag {
		Default				= 0,
		Force				= DB_FORCE,
		UseEnvironment		= DB_USE_ENVIRON,
		UseEnvironmentRoot	= DB_USE_ENVIRON_ROOT
	}

	enum DBOperationFlag {
		Default				= 0,
		AutoCommit			= DB_AUTO_COMMIT
	}

	enum FailCheckFlag {
		Default				= 0
	}

	enum ResetFlag {
		Default				= 0,
		Encrypt				= DB_ENCRYPT
	}

	enum StatFlag {
		All					= DB_STAT_ALL,
		Clear				= DB_STAT_CLEAR,
		Subsystem			= DB_STAT_SUBSYSTEM
	}

	enum TransactionCheckpointFlag {
		Default				= 0,
		Force				= DB_FORCE
	}

	enum TransactionRecoverFlag {
		Next				= DB_NEXT,
		Prev				= DB_PREV
	}


	/**
	 * Throws: BerkeleyDBError
	 */
	this(CreateFlag flags = CreateFlag.Default)
	{
		int ret = db_env_create(&env, cast(u_int32_t)flags);
		checkBdbError("create environment", ret);
		closed = true;
	}

	~this()
	{
		close();
	}

	///////////////////////////////////////////////
	// Database Environment Operations
	///////////////////////////////////////////////

	/**
	 * Open environment
	 */
	void open(char[] home, OpenFlag flags, int mode = 0)
	{
		int ret = env.open(env, home.toStringz(), cast(u_int32_t)flags, mode);
		checkBdbError("open environment: " ~ home, ret);
		closed = false;
	}

	/**
	 * Close environment
	 */
	void close(CloseFlag flags = CloseFlag.Default)
	{
		if (!closed) {
			int ret = env.close(env, cast(u_int32_t)flags);
			checkBdbError("close environment", ret);
			closed = true;
		}
	}

	/**
	 * Remove environment
	 */
	void remove(char[] home, RemoveFlag flags)
	{
		int ret = env.remove(env, home.toStringz(), cast(u_int32_t)flags);
		checkBdbError("remove environment home: " ~ home, ret);
	}

	/**
	 * Get environment home path
	 * Returns: environment home path string
	 */
	char[] get_home()
	{
		char* home;
		int ret = env.get_home(env, &home);
		checkBdbError("get_home", ret);
		return home[0..strlen(home)].dup;
	}

	/**
	 * Get environment open flags
	 */
	OpenFlag get_open_flags()
	{
		u_int32_t flags;
		int ret = env.get_open_flags(env, &flags);
		checkBdbError("get_open_flags", ret);
		return cast(OpenFlag)flags;
	}

	void dbremove(Transaction txn, char[] file, char[] database, DBOperationFlag flags)
	{
		DB_TXN* _txn = null;
		char* _file = null;
		char* _database = null;
		if (txn) _txn = txn._txn();
		if (file) _file = file.toStringz();
		if (database) _database = database.toStringz();

		int ret = env.dbremove(env, _txn, _file, _database, cast(u_int32_t)flags);
		checkBdbError("dbremove", ret);
	}

	void dbrename(Transaction txn, char[] file, char[] database, char[] newname, DBOperationFlag flags)
	{
		DB_TXN* _txn = null;
		char* _file = null;
		char* _database = null;
		char* _newname = null;
		if (txn) _txn = txn._txn();
		if (file) _file = file.toStringz();
		if (database) _database = database.toStringz();
		if (newname) _newname = newname.toStringz();

		int ret = env.dbrename(env, _txn, _file, _database, _newname, cast(u_int32_t)flags);
		checkBdbError("rename", ret);
	}

	void failchk(FailCheckFlag flags = FailCheckFlag.Default)
	{
		int ret = env.failchk(env, cast(u_int32_t)flags);
		checkBdbError("failchk", ret);
	}

	void fileid_reset(char[] file, ResetFlag flags)
	{
		char* _file = null;
		if (file) _file = file.toStringz();
		int ret = env.fileid_reset(env, _file, cast(u_int32_t)flags);
		checkBdbError("fileid_reset", ret);
	}

	void lsn_reset(char[] file, ResetFlag flags)
	{
		char* _file = null;
		if (file) _file = file.toStringz();
		int ret = env.lsn_reset(env, _file, cast(u_int32_t)flags);
		checkBdbError("lsn_reset", ret);
	}

	void stat_print(StatFlag flags)
	{
		int ret = env.stat_print(env, cast(u_int32_t)flags);
		checkBdbError("stat_print", ret);
	}

	char[] db_version()
	{
		char* ver = .db_version(cast(int*)null, cast(int*)null, cast(int*)null);
		return ver[0..strlen(ver)].dup;
	}

	char[] db_version(out int major, out int minor, out int patch)
	{
		char* ver = .db_version(&major, &minor, &patch);
		return ver[0..strlen(ver)].dup;
	}

	int db_version_major()
	{
		int major;
		.db_version(&major, null, null);
		return major;
	}

	int db_version_minor()
	{
		int minor;
		.db_version(null, &minor, null);
		return minor;
	}

	int db_version_patch()
	{
		int patch;
		.db_version(null, null, &patch);
		return patch;
	}

	void set_cachesize(uint gbytes, uint bytes, int ncache)
	{
		int ret = env.set_cachesize(env, gbytes, bytes, ncache);
		checkBdbError("set_cachesize", ret);
	}

	void get_cachesize(out uint gbytes, out uint bytes, out int ncache)
	{
		int ret = env.get_cachesize(env, &gbytes, &bytes, &ncache);
		checkBdbError("get_cachesize", ret);
	}

	void set_data_dir(char[] dir) {
		int ret = env.set_data_dir(env, toStringz(dir));
		checkBdbError("set data_dir", ret);
	}

	char[][] get_data_dirs() {
		char[][] dirs;
		char** p;
		int ret = env.get_data_dirs(env, &p);
		checkBdbError("get data_dirs", ret);
		while(*p) {
			dirs ~= (*p)[0..strlen(*p)];
		}
		return dirs;
	}

	// Transaction
	Transaction begin_transaction(Transaction parent, Transaction.TransactionFlag flags = Transaction.TransactionFlag.Default) {
		return new Transaction(this, parent, flags);
	}

	void lock_timeout(db_timeout_t timeout) {
		int ret = env.set_timeout(env, timeout, DB_SET_LOCK_TIMEOUT);
		checkBdbError("set lock_timeout", ret);
	}

	db_timeout_t lock_timeout() {
		db_timeout_t timeout;
		int ret = env.get_timeout(env, &timeout, DB_SET_LOCK_TIMEOUT);
		checkBdbError("set lock_timeout", ret);
		return timeout;
	}

	void transaction_timeout(db_timeout_t timeout) {
		int ret = env.set_timeout(env, timeout, DB_SET_TXN_TIMEOUT);
		checkBdbError("set transaction_timeout", ret);
	}

	db_timeout_t transaction_timeout() {
		db_timeout_t timeout;
		int ret = env.get_timeout(env, &timeout, DB_SET_LOCK_TIMEOUT);
		checkBdbError("set transaction_timeout", ret);
		return timeout;
	}

	void transaction_max(u_int32_t max) {
		int ret = env.set_tx_max(env, max);
		checkBdbError("set transaction max", ret);
	}

	u_int32_t transaction_max() {
		u_int32_t max;
		int ret = env.get_tx_max(env, &max);
		checkBdbError("get transaction_max", ret);
		return max;
	}

	void transaction_timestamp(time_t timestamp) {
		int ret = env.set_tx_timestamp(env, &timestamp);
		checkBdbError("set transaction timestamp", ret);
	}

	time_t transaction_timestamp() {
		time_t timestamp;
		int ret = env.set_tx_timestamp(env, &timestamp);
		checkBdbError("set transaction timestamp", ret);
		return timestamp;
	}

	void transaction_checkpoint(u_int32_t kbyte, u_int32_t min, TransactionCheckpointFlag flags = TransactionCheckpointFlag.Default) {
		int ret = env.txn_checkpoint(env, kbyte, min, cast(u_int32_t)flags);
		checkBdbError("transaction_checkpoint", ret);
	}

	ssize_t transaction_recover(DB_PREPLIST[] preplist, TransactionRecoverFlag flags) {
		ssize_t retval;
		int ret = env.txn_recover(env, preplist.ptr, preplist.length, &retval, cast(u_int32_t)flags);
		checkBdbError("transaction_recover", ret);
		return retval;
	}

	DB_TXN_STAT* stat(StatFlag flags) {
		DB_TXN_STAT* retval;
		int ret = env.txn_stat(env, &retval, cast(u_int32_t)flags);
		checkBdbError("stat", ret);
		return retval;
	}

	DB_ENV* _env()
	{
		return env;
	}

private:
	DB_ENV* env;
	bool closed;
}

